package com.igeek.ch02.servlet;


import com.igeek.ch02.entity.Items;
import com.igeek.ch02.service.ItemsService;
import com.igeek.ch02.utils.DateConverterUtils;
import com.igeek.ch02.vo.PageVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 图片上传步骤
 * 1.表单 enctype="multipart/form-data"  以二进制数据传递
 * 2.input type="file" 上传图片
 * 3.@MultipartConfig 代表当前Servlet支持文件上传
 * 4.先收集普通域数据 、 再收集文件上传数据
 */
@MultipartConfig
@WebServlet(name = "ItemsServlet", value = "/items")
public class ItemsServlet extends HttpServlet {

    private ItemsService itemsService = new ItemsService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method!=null && !method.equals("")){
            switch (method){
                case "viewAll":
                    //当前页码
                    String currentStr = request.getParameter("current");
                    int current = 0;
                    if(currentStr==null){
                        current = 1;  //默认显示第一页
                    }else{
                        current = Integer.parseInt(currentStr);
                    }
                    //条件
                    String query = request.getParameter("query");
                    if (query==null){
                        query = "";  //默认查询所有
                    }

                    //业务调用
                    PageVO<Items> vo = itemsService.fenye(current, query);
                    request.setAttribute("vo" , vo);
                    request.getRequestDispatcher("/items/itemsList.jsp").forward(request,response);
                    break;
                case "viewOne":
                    int id = Integer.parseInt(request.getParameter("id"));
                    Items items = itemsService.findOne(id);
                    request.setAttribute("items",items);
                    request.getRequestDispatcher("/items/editItem.jsp").forward(request , response);
                    break;
                case "update":
                    //先处理普通作用域数据
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    ConvertUtils.register(new DateConverterUtils() , Date.class);
                    Items item = new Items();
                    try {
                        BeanUtils.populate(item , parameterMap);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }

                    //再处理文件上传
                    Part part = request.getPart("file");
                    if(part!=null){
                        String oldName = part.getHeader("content-disposition");
                        System.out.println("oldName = "+oldName);     // 上传图片 form-data; name="file"; filename="map.png"
                        if(oldName!=null && oldName.indexOf(".")>0){  // 未上传   form-data; name="file"; filename=""
                            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf(".") , oldName.length()-1);

                            //商品设置图片
                            item.setPic("/pic/"+newName);
                            //图片服务器上传递一份
                            part.write("D:\\CodeFile\\igeekhome\\testJavaee\\JSPicture\\"+newName);
                        }else{
                            String pic = itemsService.findOne(item.getId()).getPic();
                            if(pic!=null && !pic.equals("")){
                                item.setPic(pic);
                            }
                        }
                    }

                    //更新

                    boolean flag = itemsService.updateItemsById(item);
                    if(flag){
                        //响应重定向  禁止重复提交表单
                        response.sendRedirect("/items?method=viewAll");
                    }else{
                        //回显商品信息
                        request.setAttribute("items",item);
                        request.getRequestDispatcher("/items/editItem.jsp").forward(request , response);
                    }
                    break;


            }
        }
    }
}
